package cz.zcu.fav.rat.managed.converter;

import java.util.Iterator;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import cz.zcu.fav.rat.beans.Object;
import cz.zcu.fav.rat.dataaccess.service.ObjectService;
import cz.zcu.fav.rat.managed.bean.SpringBeanFactory;

@FacesConverter(value = "objectConverter")
public class ObjectConverter implements Converter
{
	private transient ObjectService objectService;
	
	public ObjectService getObjectService()
	{
		if (objectService == null)
		{
			objectService = SpringBeanFactory.getInstance()
					.<ObjectService> getBean("objectService",
							ObjectService.class);
		}
		return objectService;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value)
	{
		Iterator<Object> it = getObjectService().findAllObjectsByIdentifier(value).iterator();
		if (it.hasNext())
		{
			return it.next();
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			java.lang.Object value)
	{
		return ((Object) value).getIdentifier();
	}
}